package org.example.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Configuration
public class RedisBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisBean.class);
    private static final String ENDPOINTS = "redis.endpoints";
    private static final String PASSWORD = "redis.password";
    private static final String TIMEOUT = "redis.timeout";
    private static final String MAX_ACTIVE = "redis.max-active";
    private static final String MAX_IDLE = "redis.max-idle";
    @Autowired
    private Environment env;

    @Bean(name = "jedisPools")
    public List<JedisPool> jedisPools() {
        // TODO: 解密没做
        // String password = encryptUtil.decryptValue(environment.getProperty(PASSWORD));
        String endpoints = env.getProperty(Objects.requireNonNull(ENDPOINTS));
        String password = env.getProperty(Objects.requireNonNull(PASSWORD));
        int timeout = Integer.parseInt(Objects.requireNonNull(env.getProperty(TIMEOUT)));
        int maxActive = Integer.parseInt(Objects.requireNonNull(env.getProperty(MAX_ACTIVE)));
        int maxIdle = Integer.parseInt(Objects.requireNonNull(env.getProperty(MAX_IDLE)));

        List<JedisPool> jedisPools = new ArrayList<>();
        for (String each : endpoints.split(",")) {
            JedisPoolConfig jpc = new JedisPoolConfig();
            jpc.setMaxTotal(maxActive);
            jpc.setMaxIdle(maxIdle);
            String[] endpoint = each.split(":");
            JedisPool jp = new JedisPool(jpc, endpoint[0], Integer.parseInt(endpoint[1]), timeout, password);
            jedisPools.add(jp);
        }

        return jedisPools;
    }
}
